package com.mmall.example.aqs.countDownLatch;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 同步组件： countDownLatch
 * Created by megan on 2018/4/29.
 */
@Slf4j
public class CountDownLatchExample {

    private static int threadCount = 200;

    public static void main(String[] args) throws Exception {
        /** 定义一个线程池 **/
        ExecutorService exec = Executors.newCachedThreadPool();

        /** 定义一个闭锁的实例 **/
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for(int i = 0 ; i < threadCount; i++){
            final int threadNum = i;
            exec.execute(() -> {
                try {
                    test(threadNum);
                } catch (Exception e) {
                    log.info("exception:{}",e);
                }finally {
                    countDownLatch.countDown();
                }
            });
        }
        /** 保证前面的线程执行完成之后执行 **/
        countDownLatch.await();
        log.info("====finish====");
        exec.shutdown();
    }

    private static void test(int threadNum) throws Exception {
        Thread.sleep(10);
        log.info("{}",threadNum);
        Thread.sleep(10);
    }
}
